<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">




<script>
    (function(){
        if(''){
            if (prompt('请输入文章密码') !== ''){
                alert('密码错误！');
                history.back();
            }
        }
    })();
  </script>






<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />



  <link rel="icon" type="image/png" sizes="32x32" href="/favicon.ico?v=5.1.4">







  <meta name="keywords" content="iOS," />





  <link rel="alternate" href="/atom.xml" title="Swift社区" type="application/atom+xml" />






<meta name="description" content="Swift的总体目标是既强大到可以用于底层系统编程，又足够容易让初学者学习，这有时会导致相当有趣的情况——当Swift的类型系统的力量要求我们部署相当高级的技术来解决乍一看可能更微不足道的问题。 大多数Swift开发人员会在某一时刻或另一时刻（通常是马上，而不是日后）会遇到这样一种情况，即需要某种形式的类型擦除才能引用通用协议。从本周开始，让我们看一下是什么使类型擦除在Swift中成为必不可少的技">
<meta name="keywords" content="iOS">
<meta property="og:type" content="article">
<meta property="og:title" content="Swift 中风味各异的类型擦除">
<meta property="og:url" content="https://fanbaoying.github.io/Swift-中风味各异的类型擦除/index.html">
<meta property="og:site_name" content="Swift社区">
<meta property="og:description" content="Swift的总体目标是既强大到可以用于底层系统编程，又足够容易让初学者学习，这有时会导致相当有趣的情况——当Swift的类型系统的力量要求我们部署相当高级的技术来解决乍一看可能更微不足道的问题。 大多数Swift开发人员会在某一时刻或另一时刻（通常是马上，而不是日后）会遇到这样一种情况，即需要某种形式的类型擦除才能引用通用协议。从本周开始，让我们看一下是什么使类型擦除在Swift中成为必不可少的技">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2022-03-31T02:06:26.201Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Swift 中风味各异的类型擦除">
<meta name="twitter:description" content="Swift的总体目标是既强大到可以用于底层系统编程，又足够容易让初学者学习，这有时会导致相当有趣的情况——当Swift的类型系统的力量要求我们部署相当高级的技术来解决乍一看可能更微不足道的问题。 大多数Swift开发人员会在某一时刻或另一时刻（通常是马上，而不是日后）会遇到这样一种情况，即需要某种形式的类型擦除才能引用通用协议。从本周开始，让我们看一下是什么使类型擦除在Swift中成为必不可少的技">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://fanbaoying.github.io/Swift-中风味各异的类型擦除/"/>





  <title>Swift 中风味各异的类型擦除 | Swift社区</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    
    <a href="https://github.com/SwiftCommunityRes" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
    
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Swift社区</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">做最好的 Swift 社区</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://fanbaoying.github.io/Swift-中风味各异的类型擦除/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Swift社区">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://avatars.githubusercontent.com/u/84354365?v=4">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Swift社区">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Swift 中风味各异的类型擦除</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2022-03-31T10:03:18+08:00">
                2022-03-31
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Swift/" itemprop="url" rel="index">
                    <span itemprop="name">Swift</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                <!-- 
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                -->
                <span title="字数统计">
                  数字统计 2,953字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>

                <!-- 
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                --> 

                <span title="阅读时长">
                  阅读时长 11分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>Swift的总体目标是既强大到可以用于底层系统编程，又足够容易让初学者学习，这有时会导致相当有趣的情况——当Swift的类型系统的力量要求我们部署相当高级的技术来解决乍一看可能更微不足道的问题。</p>
<p>大多数Swift开发人员会在某一时刻或另一时刻（通常是马上，而不是日后）会遇到这样一种情况，即需要某种形式的类型擦除才能引用通用协议。从本周开始，让我们看一下是什么使类型擦除在Swift中成为必不可少的技术，然后继续探索实现它的不同 <em>“风味(Flavors)”</em>，以及每种风味为何各有优缺点。</p>
<a id="more"></a>
<h2 id="什么时候需要类型擦除？"><a href="#什么时候需要类型擦除？" class="headerlink" title="什么时候需要类型擦除？"></a>什么时候需要类型擦除？</h2><p>一开始，<em>“类型擦除”</em>一词似乎与 Swift 给我们的关注类型和编译时类型安全性的第一感觉相反，因此，最好将其描述为<em>隐藏类型</em>，而不是完全擦除它们。目的是使我们能够更轻松地与通用协议进行交互，因为这些通用协议对将要实现它们的各种类型具有特定的要求。</p>
<p>以标准库中的<code>Equatable</code>协议为例。由于所有目的都是为了根据相等性比较两个相同类型的值，因此<code>Self</code>元类型为其唯一要求的参数：<br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">protocol</span> <span class="title">Equatable</span> </span>&#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="function"><span class="keyword">func</span> ==<span class="params">(lhs: <span class="keyword">Self</span>, rhs: <span class="keyword">Self</span>)</span></span> -&gt; <span class="type">Bool</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>上面的代码使任何类型都可以符合<code>Equatable</code>，同时仍然需要<code>==</code>运算符两侧的值都为同一类型，因为在实现上述方法时符合协议的每种类型都必须“填写”自己的类型：<br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">extension</span> <span class="title">User</span>: <span class="title">Equatable</span> </span>&#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="function"><span class="keyword">func</span> ==<span class="params">(lhs: User, rhs: User)</span></span> -&gt; <span class="type">Bool</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> lhs.id == rhs.id</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>该方法的优点在于，它不可能意外地比较两个不相关的相等类型（例如 <code>User</code> 和 <code>String</code> ），但是，它也导致不可能将<code>Equatable</code>引用为独立协议（例如创建 <code>[Equatable]</code> ），因为编译器需要知道实际上确切符合协议的确切类型才能使用它。</p>
<p>当协议包含关联的类型时，也是如此。例如，在这里我们定义了一个<code>Request</code>协议，使我们可以在一个统一的实现中隐藏各种形式的数据请求（例如网络调用，数据库查询和缓存提取）：<br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">protocol</span> <span class="title">Request</span> </span>&#123;</span><br><span class="line">    associatedtype <span class="type">Response</span></span><br><span class="line">    associatedtype <span class="type">Error</span>: <span class="type">Swift</span>.<span class="type">Error</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">typealias</span> <span class="type">Handler</span> = (<span class="type">Result</span>&lt;<span class="type">Response</span>, <span class="type">Error</span>&gt;) -&gt; <span class="type">Void</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">perform</span><span class="params">(then handler: @escaping Handler)</span></span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>上面的方法为我们提供了与<code>Equatable</code>相同的权衡方法——它非常强大，因为它使我们能够为任何类型的请求创建通用抽象，但也使得无法直接引用<code>Request</code>协议本身，例如这：<br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">RequestQueue</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 报错: protocol 'Request' can only be used as a generic</span></span><br><span class="line">    <span class="comment">// constraint because it has Self or associated type requirements</span></span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">add</span><span class="params">(<span class="number">_</span> request: Request,</span></span></span><br><span class="line"><span class="function"><span class="params">             handler: @escaping Request.Handler)</span></span> &#123;</span><br><span class="line">        ...</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>解决上述问题的一种方法是完全按照报错消息的内容进行操作，即不直接引用<code>Request</code>，而是将其用作一般约束：<br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">RequestQueue</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">add</span>&lt;R: Request&gt;<span class="params">(<span class="number">_</span> request: R,</span></span></span><br><span class="line"><span class="function"><span class="params">                         handler: @escaping R.Handler)</span></span> &#123;</span><br><span class="line">        ...</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>上面的方法起作用了，因为现在编译器能够保证所传递的处理程序确实与作为请求传递的<code>Request</code>实现兼容——因为它们都基于泛型<code>R</code>，而后者又被限制为符合<code>Request</code>协议。</p>
<p><strong>但是</strong>，尽管我们解决了方法的签名问题，但仍然无法对传递的请求进行实际的处理，因为我们无法将其存储为<code>Request</code>属性或<code>[Request]</code>数组，这将使继续构建我们的<code>RequestQueue</code>变得困难。也就是说，除非我们开始进行类型擦除。</p>
<h2 id="通用包装器类型擦除"><a href="#通用包装器类型擦除" class="headerlink" title="通用包装器类型擦除"></a>通用包装器类型擦除</h2><p>我们将探讨的第一种类型擦除实际上并没有涉及擦除任何类型，而是将它们包装在一个我们可以更容易引用的通用类型中。继续从之前的<code>RequestQueue</code>示例开始，我们首先创建该包装器类型——该包装器类型将捕获每个请求的<code>perform</code>方法作为闭包，以及在请求完成后应调用的处理程序：<br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 这将使我们将 Request 协议的实现包装在一个</span></span><br><span class="line"><span class="comment">// 与 Request 协议具有相同的响应和错误类型的泛型中</span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">AnyRequest</span>&lt;<span class="title">Response</span>, <span class="title">Error</span>: <span class="title">Swift</span>.<span class="title">Error</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">typealias</span> <span class="type">Handler</span> = (<span class="type">Result</span>&lt;<span class="type">Response</span>, <span class="type">Error</span>&gt;) -&gt; <span class="type">Void</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">let</span> perform: (@escaping <span class="type">Handler</span>) -&gt; <span class="type">Void</span></span><br><span class="line">    <span class="keyword">let</span> handler: <span class="type">Handler</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>接下来，我们还将把<code>RequestQueue</code>本身转换为相同的<code>Response</code>和<code>Error</code>类型的泛型——使得编译器可以保证所有关联的类型和泛型类型对齐，从而使我们可以将请求存储为独立的引用并作为数组的一部分——像这样：<br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">RequestQueue</span>&lt;<span class="title">Response</span>, <span class="title">Error</span>: <span class="title">Swift</span>.<span class="title">Error</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">typealias</span> <span class="type">TypeErasedRequest</span> = <span class="type">AnyRequest</span>&lt;<span class="type">Response</span>, <span class="type">Error</span>&gt;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">var</span> queue = [<span class="type">TypeErasedRequest</span>]()</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">var</span> ongoing: <span class="type">TypeErasedRequest</span>?</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 我们修改了'add'方法，以包含一个'where'子句，</span></span><br><span class="line">    <span class="comment">// 该子句确保传递的请求已关联的类型与队列的通用类型匹配。</span></span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">add</span>&lt;R: Request&gt;<span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">        <span class="number">_</span> request: R,</span></span></span><br><span class="line"><span class="function"><span class="params">        handler: @escaping R.Handler</span></span></span><br><span class="line"><span class="function"><span class="params">    )</span></span> <span class="keyword">where</span> <span class="type">R</span>.<span class="type">Response</span> == <span class="type">Response</span>, <span class="type">R</span>.<span class="type">Error</span> == <span class="type">Error</span> &#123;</span><br><span class="line">        <span class="comment">//要执行类型擦除，我们只需创建一个实例'AnyRequest'，</span></span><br><span class="line">        <span class="comment">//然后将其传递给基础请求将“perform”方法与处理程序一起作为闭包。</span></span><br><span class="line">        <span class="keyword">let</span> typeErased = <span class="type">AnyRequest</span>(</span><br><span class="line">            perform: request.perform,</span><br><span class="line">            handler: handler</span><br><span class="line">        )</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 由于我们要实现队列，因此我们不想一次有两个请求，</span></span><br><span class="line">        <span class="comment">// 所以将请求保存下拉，以防稍后有一个正在执行的请求。</span></span><br><span class="line">        <span class="keyword">guard</span> ongoing == <span class="literal">nil</span> <span class="keyword">else</span> &#123;</span><br><span class="line">            queue.append(typeErased)</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        perform(typeErased)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">func</span> <span class="title">perform</span><span class="params">(<span class="number">_</span> request: TypeErasedRequest)</span></span> &#123;</span><br><span class="line">        ongoing = request</span><br><span class="line"></span><br><span class="line">        request.perform &#123; [<span class="keyword">weak</span> <span class="keyword">self</span>] result <span class="keyword">in</span></span><br><span class="line">            request.handler(result)</span><br><span class="line">            <span class="keyword">self</span>?.ongoing = <span class="literal">nil</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">// 如果队列不为空，则执行下一个请求</span></span><br><span class="line">            ...</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<blockquote>
<p>请注意，上面的示例以及本文中的其他示例代码都不是线程安全的——为了使事情变得简单。有关线程安全的更多信息，请查看<a href="https://www.swiftbysundell.com/articles/avoiding-race-conditions-in-swift" target="_blank" rel="noopener">“避免在Swift 中竞争条件”</a>。</p>
</blockquote>
<p>上面的方法效果很好，但有一些缺点。我们不仅引入了新的<code>AnyRequest</code>类型，还需要将<code>RequestQueue</code>转换为泛型。这给我们带来了一点灵活性，因为我们现在只能将任何给定的队列用于具有相同 响应/错误类型 组合的请求。具有讽刺意味的是，如果我们想组成多个实例，将来可能还需要我们自己实现队列擦除。</p>
<h2 id="闭包类型擦除"><a href="#闭包类型擦除" class="headerlink" title="闭包类型擦除"></a>闭包类型擦除</h2><p>我们不引入包装类型，而是让我们看一下如何使用闭包来实现相同的类型擦除，同时还要使我们的<code>RequestQueue</code>非泛型且通用，足以用于不同类型的请求。</p>
<p>使用闭包擦除类型时，其思想是捕获在闭包内部执行操作所需的所有类型信息，并使该闭包仅接受非泛型（甚至是<code>Void</code>）输入。这样一来，我们就可以引用，存储和传递该功能，而无需实际知道功能内部会发生什么，从而为我们提供了更强大的灵活性。</p>
<p>更新<code>RequestQueue</code>以使用基于闭包的类型擦除的方法如下：<br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">RequestQueue</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">var</span> queue = [() -&gt; <span class="type">Void</span>]()</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">var</span> isPerformingRequest = <span class="literal">false</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">add</span>&lt;R: Request&gt;<span class="params">(<span class="number">_</span> request: R,</span></span></span><br><span class="line"><span class="function"><span class="params">                         handler: @escaping R.Handler)</span></span> &#123;</span><br><span class="line">        <span class="comment">// 此闭包将同时捕获请求及其处理程序，而不会暴露任何类型信息</span></span><br><span class="line">        <span class="comment">// 在其外部，提供完全的类型擦除。</span></span><br><span class="line">        <span class="keyword">let</span> typeErased = &#123;</span><br><span class="line">            request.perform &#123; [<span class="keyword">weak</span> <span class="keyword">self</span>] result <span class="keyword">in</span></span><br><span class="line">                handler(result)</span><br><span class="line">                <span class="keyword">self</span>?.isPerformingRequest = <span class="literal">false</span></span><br><span class="line">                <span class="keyword">self</span>?.performNextIfNeeded()</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        queue.append(typeErased)</span><br><span class="line">        performNextIfNeeded()</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">func</span> <span class="title">performNextIfNeeded</span><span class="params">()</span></span> &#123;</span><br><span class="line">        <span class="keyword">guard</span> !isPerformingRequest &amp;&amp; !queue.isEmpty <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        isPerformingRequest = <span class="literal">true</span></span><br><span class="line">        <span class="keyword">let</span> closure = queue.removeFirst()</span><br><span class="line">        closure()</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>虽然过分依赖闭包来捕获功能和状态有时会使我们的代码难以调试，但也可能使完全封装类型信息成为可能——使得像<code>RequestQueue</code>这样的对象可以在没有真正了解在底层工作的类型的任何细节的情况下进行工作。</p>
<blockquote>
<p>有关基于闭包的类型擦除及其更多不同方法的更多信息，请查看<a href="https://www.jianshu.com/p/8464cea6abb5" target="_blank" rel="noopener">“Swift 使用闭包实现类型擦除”</a>。</p>
</blockquote>
<h2 id="外部特化（External-specialization）"><a href="#外部特化（External-specialization）" class="headerlink" title="外部特化（External specialization）"></a>外部特化（External specialization）</h2><p>到目前为止，我们已经在<code>RequestQueue</code>本身中执行了所有类型擦除，这有一些优点——它可以让任何外部代码使用我们的队列，而不需要知道我们使用什么类型的类型擦除。然而，有时在将协议实现传递给API之前进行一些轻量级转换，既可以使事情变得更简单，又可以巧妙地封装类型擦除代码本身。</p>
<p>对于我们的<code>RequestQueue</code>，一种方法是要求在将每个<code>Request</code>实现添加到队列之前对其进行特化——这将把它转换为<code>RequestOperation</code>，如下所示：<br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">RequestOperation</span> </span>&#123;</span><br><span class="line">    <span class="keyword">fileprivate</span> <span class="keyword">let</span> closure: (@escaping () -&gt; <span class="type">Void</span>) -&gt; <span class="type">Void</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">perform</span><span class="params">(then handler: @escaping <span class="params">()</span></span></span> -&gt; <span class="type">Void</span>) &#123;</span><br><span class="line">        closure(handler)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>与我们之前使用闭包在<code>RequestQueue</code>中执行类型擦除的方式类似，上面的<code>RequestOperation</code>类型将使我们能够在扩展<code>Request</code>时执行该操作：<br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">extension</span> <span class="title">Request</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">makeOperation</span><span class="params">(with handler: @escaping Handler)</span></span> -&gt; <span class="type">RequestOperation</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="type">RequestOperation</span> &#123; finisher <span class="keyword">in</span></span><br><span class="line">            <span class="comment">// 我们其实想在这里捕获'self'，因为不这样话</span></span><br><span class="line">            <span class="comment">// 我们将冒着无法保留基本请求的风险。</span></span><br><span class="line">            <span class="keyword">self</span>.perform &#123; result <span class="keyword">in</span></span><br><span class="line">                handler(result)</span><br><span class="line">                finisher()</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>上述方法的优点在于，无论是公共API还是内部实现，它都让我们的<code>RequestQueue</code>更加简单。它现在可以完全专注于作为一个队列，而不必关心任何类型的类型擦除：<br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">RequestQueue</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">var</span> queue = [<span class="type">RequestOperation</span>]()</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">var</span> ongoing: <span class="type">RequestOperation</span>?</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 因为类型擦除现在发生在request被传递给 queue 之前，</span></span><br><span class="line">    <span class="comment">// 它可以简单地接受一个具体的“RequestOperation”的实例。</span></span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">add</span><span class="params">(<span class="number">_</span> operation: RequestOperation)</span></span> &#123;</span><br><span class="line">        <span class="keyword">guard</span> ongoing == <span class="literal">nil</span> <span class="keyword">else</span> &#123;</span><br><span class="line">            queue.append(operation)</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        perform(operation)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">func</span> <span class="title">perform</span><span class="params">(<span class="number">_</span> operation: RequestOperation)</span></span> &#123;</span><br><span class="line">        ongoing = operation</span><br><span class="line"></span><br><span class="line">        operation.perform &#123; [<span class="keyword">weak</span> <span class="keyword">self</span>] <span class="keyword">in</span></span><br><span class="line">            <span class="keyword">self</span>?.ongoing = <span class="literal">nil</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">// 如果队列不为空，则执行下一个请求</span></span><br><span class="line">            ...</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>然而，这里的缺点是，在将每个请求添加到队列之前，我们必须手动将其转换为<code>RequestOperation</code>——虽然这不会在每个调用点添加大量代码，但这取决于必须完成相同转换的次数，它最终可能会有点像样板。</p>
<h2 id="结语"><a href="#结语" class="headerlink" title="结语"></a>结语</h2><p>尽管 Swift 提供了一个功能强大得难以置信的类型系统，可以帮助我们避免大量的bug，但有时它会让人觉得我们必须与系统抗争，才能使用通用协议之类的功能。必须进行类型擦除最初看起来像是一件不必要的杂务，但它也带来了一些好处——比如从不需要关心这些类型的代码中隐藏特定类型信息。</p>
<p>在未来，我们可能还会看到 Swift 中添加了新的特性，可以自动化创建类型擦除包装类型的过程，也可以通过使协议也被用作适当的泛型（例如能够定义像<code>Request&lt;Response，Error&gt;</code>这样的协议）来消除对它的大量需求，而不仅仅依赖于相关的类型）。</p>
<p>什么样的类型擦除是最合适的——无论是现在还是将来——当然很大程度上取决于上下文，以及我们的功能是否可以在闭包中轻松地执行，或者完整包装器类型或泛型是否更适合这个问题。</p>
<p>感谢阅读！🚀</p>

      
    </div>
    
    
    
    

    
      <div>
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      </div>
    


    
      <div>
        
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>

  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="/Swift-中风味各异的类型擦除/">Swift 中风味各异的类型擦除</a></p>
  <p><span>文章作者:</span><a href="/" title="访问 Swift社区 的个人博客">Swift社区</a></p>
  <p><span>发布时间:</span>2022年03月31日 - 10:03</p>
  <p><span>最后更新:</span>2022年03月31日 - 10:03</p>
  <p><span>原始链接:</span><a href="/Swift-中风味各异的类型擦除/" title="Swift 中风味各异的类型擦除">https://fanbaoying.github.io/Swift-中风味各异的类型擦除/</a>
    <span class="copy-path"  title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="https://fanbaoying.github.io/Swift-中风味各异的类型擦除/"  aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
      $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
        });
    });  
</script>

      </div>
    


    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat.png" alt="Swift社区 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="Swift社区 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/iOS/" rel="tag"><i class="fa fa-tag"></i> iOS</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/Swift-中风味各异的依赖注入/" rel="next" title="Swift 中风味各异的依赖注入">
                <i class="fa fa-chevron-left"></i> Swift 中风味各异的依赖注入
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/Swift-中的抽象类型和方法/" rel="prev" title="Swift 中的抽象类型和方法">
                Swift 中的抽象类型和方法 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
<span class="jiathis_txt">分享到：</span>
<a class="jiathis_button_fav">收藏夹</a>
<a class="jiathis_button_copy">复制网址</a>
<a class="jiathis_button_email">邮件</a>
<a class="jiathis_button_weixin">微信</a>
<a class="jiathis_button_qzone">QQ空间</a>
<a class="jiathis_button_tqq">腾讯微博</a>
<a class="jiathis_button_douban">豆瓣</a>
<a class="jiathis_button_share">一键分享</a>

<a href="http://www.jiathis.com/share?uid=2140465" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank">更多</a>
<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
var jiathis_config={
  data_track_clickback:true,
  summary:"",
  shortUrl:false,
  hideMore:false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=" charset="utf-8"></script>
<!-- JiaThis Button END -->
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="https://avatars.githubusercontent.com/u/84354365?v=4"
                alt="Swift社区" />
            
              <p class="site-author-name" itemprop="name">Swift社区</p>
              <p class="site-description motion-element" itemprop="description">我们的使命是做一个最专业最权威的 Swift 中文社区，我们的愿景是希望更多的人学习和使用Swift。我们会分享以 Swift 实战、SwiftUI、Swift 基础为核心的技术干货，不忘初心，牢记使命。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">187</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">11</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://blog.csdn.net/qq_36478920" target="_blank" title="CSDN">
                      
                        <i class="fa fa-fw fa-heartbeat"></i>CSDN</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://juejin.im/user/5a30d987f265da430d580126" target="_blank" title="掘金">
                      
                        <i class="fa fa-fw fa-spinner"></i>掘金</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/fanbaoying" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.zhihu.com/people/swift-community" target="_blank" title="知乎">
                      
                        <i class="fa fa-fw fa-heartbeat"></i>知乎</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/u/7711465033" target="_blank" title="微博">
                      
                        <i class="fa fa-fw fa-weibo"></i>微博</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://mp.weixin.qq.com/mp/appmsgalbum?__biz=MzAxNzgzNTgwMw==&action=getalbum&album_id=2024314764775981057" target="_blank" title="公众号">
                      
                        <i class="fa fa-fw fa-heartbeat"></i>公众号</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://github.com/SwiftCommunityRes/SwiftWeekly" title="SwiftWeekly" target="_blank">SwiftWeekly</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://github.com/SwiftCommunityRes/article-ios" title="Article-ios" target="_blank">Article-ios</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://github.com/SwiftCommunityRes/SwiftUI-Book" title="SwiftUI-Book" target="_blank">SwiftUI-Book</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#什么时候需要类型擦除？"><span class="nav-number">1.</span> <span class="nav-text">什么时候需要类型擦除？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#通用包装器类型擦除"><span class="nav-number">2.</span> <span class="nav-text">通用包装器类型擦除</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#闭包类型擦除"><span class="nav-number">3.</span> <span class="nav-text">闭包类型擦除</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#外部特化（External-specialization）"><span class="nav-number">4.</span> <span class="nav-text">外部特化（External specialization）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#结语"><span class="nav-number">5.</span> <span class="nav-text">结语</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2024</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Swift社区</span>

  
</div>

<!-- 
<div class="powered-by">
  <i class="fa fa-user-md">
  </i>
  <span id="busuanzi_container_site_uv">
    已有<span id="busuanzi_value_site_uv"></span>人来访
  </span>

</div>


  <span class="post-meta-divider">|</span>


<div class="powered-by">
  <i class="fa fa-eye"></i>
  <span id="busuanzi_container_site_pv">
      访问量<span id="busuanzi_value_site_pv"></span>次
  </span>
</div>



  <span class="post-meta-divider">|</span>


-->

<div class="theme-info">
  <i class="fa fa-pencil"></i>
  <span class="post-count">博客全站共361.6k字</span>
</div>


<!-- 
  <span class="post-meta-divider">|</span>



  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>



-->

        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
